<template>
  <div class="word-card-container" v-if="word">
    <div class="word-card"
      :class="{ 'flipped-1': currentFace === 1, 'flipped-2': currentFace === 2, 'flipped-3': currentFace === 3 }"
      v-touch:swipe.left="handleSwipeLeft" v-touch:swipe.right="handleSwipeRight" v-touch:swipe.up="handleSwipeUp"
      ref="cardElement">
      
      <!-- 使用子组件替代原来的卡片面 -->
      <card-face-word 
        :word="word" 
        :swipe-animation="swipeAnimation" 
        :enter-animation="enterAnimation"
        @play-word-audio="playWordAudio" />
        
      <card-face-image 
        :word="word" 
        :swipe-animation="swipeAnimation" 
        :enter-animation="enterAnimation" />
        
      <card-face-example 
        :word="word" 
        :swipe-animation="swipeAnimation" 
        :enter-animation="enterAnimation"
        @play-example-audio="playExampleAudio" />
        
      <card-face-explanation 
        :word="word" 
        :swipe-animation="swipeAnimation" 
        :enter-animation="enterAnimation"
        @notes-saved="handleNotesSaved" />
    </div>

    <!-- 圆圈导航 -->
    <circle-navigator :currentFace="currentFace" :totalFaces="4" @navigate="navigateToFace" />
  </div>
  <div class="loading-container" v-else>
    <p>加载中...</p>
  </div>
</template>

<script>
import CircleNavigator from './CircleNavigator.vue';
import CardFaceWord from './word-card/CardFaceWord.vue';
import CardFaceImage from './word-card/CardFaceImage.vue';
import CardFaceExample from './word-card/CardFaceExample.vue';
import CardFaceExplanation from './word-card/CardFaceExplanation.vue';

// 导入样式
import './word-card/WordCardStyles.css';

export default {
  name: 'WordCard',
  components: {
    CircleNavigator,
    CardFaceWord,
    CardFaceImage,
    CardFaceExample,
    CardFaceExplanation
  },
  props: {
    word: {
      type: Object,
      required: true,
      default: () => ({
        text: 'Example',
        phonetic: '/ɪɡˈzɑːmpl/',
        difficulty: 3,
        imageUrl: '',
        meaning: '示例',
        type: '名词',
        animationUrl: '',
        example: 'This is an example.',
        exampleTranslation: '这是一个例子。',
        audioUrl: '',
        exampleAudioUrl: '',
        explanation: '',
        tags: []
      })
    }
  },
  data() {
    return {
      currentFace: 0,
      swipeAnimation: '',
      isAnimating: false,
      enterAnimation: ''
    }
  },
  methods: {
    navigateToFace(faceIndex) {
      this.currentFace = faceIndex;
    },
    handleSwipeLeft() {
      console.log('检测到左滑');
      this.currentFace = (this.currentFace + 1) % 4;
    },
    handleSwipeRight() {
      console.log('检测到右滑');
      this.currentFace = (this.currentFace - 1 + 4) % 4;
    },
    handleSwipeUp(event) {
      if (this.isAnimating) return; // 如果动画正在进行中，则不执行
      
      this.isAnimating = true; // 标记动画开始
      
      // 设置滑动动画类型
      if (event === 'top') {
        this.swipeAnimation = 'swipe-up';
        
        // 应用动画后延迟执行
        setTimeout(() => {
          // 触发切换单词事件
          this.$emit('prevWord');
          
          // 设置入场动画
          this.enterAnimation = 'enter-from-bottom';
          
          // 延迟一段时间后重置所有动画状态
          setTimeout(() => {
            this.swipeAnimation = '';
            setTimeout(() => {
              this.enterAnimation = '';
              this.isAnimating = false;
            }, 500); // 入场动画完成时间
          }, 300); // 出场动画结束后重置
        }, 300); // 等待动画执行
        
      } else if (event === 'bottom') {
        this.swipeAnimation = 'swipe-down';
        
        // 应用动画后延迟执行
        setTimeout(() => {
          // 触发切换单词事件
          this.$emit('nextWord');
          
          // 设置入场动画
          this.enterAnimation = 'enter-from-top';
          
          // 延迟一段时间后重置所有动画状态
          setTimeout(() => {
            this.swipeAnimation = '';
            setTimeout(() => {
              this.enterAnimation = '';
              this.isAnimating = false;
            }, 500); // 入场动画完成时间
          }, 300); // 出场动画结束后重置
        }, 300); // 等待动画执行
      } else {
        this.isAnimating = false; // 如果没有动画，重置状态
      }
    },
    handleNotesSaved() {
      // 处理笔记保存事件
      console.log('笔记已保存');
    },
    playWordAudio() {
      if (!this.word || !this.word.audioUrl) {
        console.warn('单词音频URL不存在');
        return;
      }

      // 处理audioUrl作为文件路径的情况
      try {
        // 如果audioUrl是txt文件路径
        if (this.word.audioUrl) {
          // 使用fetch加载txt文件内容
          fetch(this.word.audioUrl)
            .then(response => {
              if (!response.ok) {
                throw new Error(`HTTP error! Status: ${response.status}`);
              }
              return response.text();
            })
            .then(audioData => {
              // 从文件内容中提取所有base64音频数据
              const base64Matches = audioData.match(/data:application\/octet-stream;base64,[^"'\s]+/g);

              if (base64Matches && base64Matches.length > 0) {
                console.log(`找到${base64Matches.length}个音频数据`);
                // 顺序播放所有音频
                this.playAudioSequentially(base64Matches);
              } else {
                console.warn('在音频文件中未找到有效的base64编码音频数据');
              }
            })
            .catch(error => {
              console.error('加载音频文件失败:', error);
            });
        } else if (this.word.audioUrl.startsWith('data:')) {
          // 直接是base64编码的情况
          let audioUrl = this.word.audioUrl;

          // 修正MIME类型
          if (audioUrl.startsWith('data:application/octet-stream;base64')) {
            audioUrl = audioUrl.replace('data:application/octet-stream;base64', 'data:audio/mpeg;base64');
          }

          const audio = new Audio(audioUrl);
          audio.play().catch(error => {
            console.error('播放单词音频失败:', error);
            if (error.name === 'NotSupportedError') {
              console.warn('浏览器不支持此音频格式');
            } else if (error.name === 'NotAllowedError') {
              console.warn('需要用户交互才能播放音频');
            }
          });
        } else {
          // 普通音频文件URL的情况
          const audio = new Audio(this.word.audioUrl);
          audio.play().catch(error => {
            console.error('播放单词音频失败:', error);
          });
        }
      } catch (error) {
        console.error('音频处理过程中出错:', error);
      }
    },
    playExampleAudio() {
      if (!this.word || !this.word.exampleAudioUrl) {
        console.warn('例句音频URL不存在');
        return;
      }

      try {
        // 如果exampleAudioUrl是txt文件路径
        if (this.word.exampleAudioUrl.endsWith('.txt')) {
          // 使用fetch加载txt文件内容
          fetch(this.word.exampleAudioUrl)
            .then(response => {
              if (!response.ok) {
                throw new Error(`HTTP error! Status: ${response.status}`);
              }
              return response.text();
            })
            .then(audioData => {
              // 从文件内容中提取base64音频数据
              const base64Match = audioData.match(/data:application\/octet-stream;base64,[^"'\s]+/);

              if (base64Match && base64Match[0]) {
                let audioUrl = base64Match[0];

                // 修改MIME类型为audio/mpeg
                audioUrl = audioUrl.replace('data:application/octet-stream;base64', 'data:audio/mpeg;base64');

                const audio = new Audio(audioUrl);
                audio.play().catch(error => {
                  console.error('播放例句音频失败:', error);
                });
              } else {
                console.warn('在例句音频文件中未找到有效的base64编码音频数据');
              }
            })
            .catch(error => {
              console.error('加载例句音频文件失败:', error);
            });
        } else if (this.word.exampleAudioUrl.startsWith('data:')) {
          // 直接是base64编码的情况
          let audioUrl = this.word.exampleAudioUrl;

          // 修正MIME类型
          if (audioUrl.startsWith('data:application/octet-stream;base64')) {
            audioUrl = audioUrl.replace('data:application/octet-stream;base64', 'data:audio/mpeg;base64');
          }

          const audio = new Audio(audioUrl);
          audio.play().catch(error => {
            console.error('播放例句音频失败:', error);
          });
        } else {
          // 普通音频文件URL的情况
          const audio = new Audio(this.word.exampleAudioUrl);
          audio.play().catch(error => {
            console.error('播放例句音频失败:', error);
          });
        }
      } catch (error) {
        console.error('例句音频处理过程中出错:', error);
      }
    },
    playAudioSequentially(audioUrls) {
      let index = 0;

      const playNextAudio = () => {
        if (index < audioUrls.length) {
          let audioUrl = audioUrls[index];

          // 修正MIME类型
          if (audioUrl.startsWith('data:application/octet-stream;base64')) {
            audioUrl = audioUrl.replace('data:application/octet-stream;base64', 'data:audio/mpeg;base64');
          }

          const audio = new Audio(audioUrl);
          audio.onended = () => {
            index++;
            playNextAudio();
          };
          audio.play().catch(error => {
            console.error('播放音频失败:', error);
          });
        }
      };

      playNextAudio();
    }
  }
}
</script>